package com.huangd.platform.modules.sys.service.impl;

import com.huangd.platform.modules.sys.dao.TblUserRoleDao;
import com.huangd.platform.modules.sys.entity.TblUserRoleEntity;
import com.huangd.platform.modules.sys.entity.to.SetUserRoleTo;
import com.huangd.platform.common.utils.MapUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huangd.platform.common.utils.PageUtils;
import com.huangd.platform.common.utils.Query;

import com.huangd.platform.modules.sys.service.TblUserRoleService;


@Service("tblUserRoleService")
public class TblUserRoleServiceImpl extends ServiceImpl<TblUserRoleDao, TblUserRoleEntity> implements TblUserRoleService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<TblUserRoleEntity> page = this.page(
                new Query<TblUserRoleEntity>().getPage(params),
                new QueryWrapper<TblUserRoleEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveOrUpdate(Integer userId, List<Integer> roleIdList) {
        //先删除用户与角色关系
        this.removeByMap(new MapUtils().put("user_id", userId));

        if(roleIdList == null || roleIdList.size() == 0){
            return ;
        }

        //保存用户与角色关系
        for(Integer roleId : roleIdList){
            TblUserRoleEntity sysUserRoleEntity = new TblUserRoleEntity();
            sysUserRoleEntity.setUserId(userId);
            sysUserRoleEntity.setRoleId(roleId);

            this.save(sysUserRoleEntity);
        }
    }

    @Override
    public List<Integer> queryRoleIdList(Long userId) {
        return baseMapper.queryRoleIdList(userId);
    }
    @Override
    public int deleteBatch(Long[] roleIds){
        return baseMapper.deleteBatch(roleIds);
    }

    @Override
    public int deletebyId(Integer userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("user_id", userId);
        return baseMapper.deleteByMap(map);
    }

    @Override
    public void saveRoles(SetUserRoleTo setUserRoleTo) {
        // 先删除
        String roleIds = setUserRoleTo.getRoleIds();
        Integer userId = setUserRoleTo.getUserId();

        this.deletebyId(userId);

        String[] split = roleIds.split(",");
        for (String s : split) {
            TblUserRoleEntity userRoleEntity = new TblUserRoleEntity();
            userRoleEntity.setUserId(setUserRoleTo.getUserId());
            userRoleEntity.setRoleId(Integer.parseInt(s));
            this.save(userRoleEntity);
        }
    }

}